<?php

namespace app\common\model\banxi\sys;

use app\common\enums\NotificationStatusEnum;
use app\common\model\common\BaseModel;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * Attachment模型
 * @property string url              文件物理路径
 * @property int quote            上传(引用)次数
 * @property int last_upload_time 最后上传时间
 */
class SysNotification extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_sys_notification';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'statusCn'
    ];
    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'isAll' => 'boolean',
        'isRead' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s'
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                        ｜
    //-----------------------------------------------------------------------------------

    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new NotificationStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->where($where)->paginate([
            'page' => $page,
            'list_rows' => $limit
        ]);
    }

    public function getInfo(array $where)
    {
        return $this->where($where)->find();
    }

    /**
     * 获取我的通知信息分页列表
     *
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $accountId 账户ID
     * @param string $accountType 账户类型
     * @param string $searchText 搜索文本
     * @return array
     */
    public function listMyInfoPage($page, $limit, $accountId, $accountType, $searchText = null)
    {
        // 构建查询
        $query = $this->alias('n')
            ->leftJoin('banxi_sys_notification_accept a', 'a.notificationId = n.id AND a.del = 0')
            ->where('n.del', 0)
            ->where(function ($query) use ($accountId, $accountType) {
                $query->where('n.isAll', 1)
                    ->whereOr(function ($query) use ($accountId, $accountType) {
                        $query->where('n.isAll', 0)
                            ->where('a.accountId', $accountId)
                            ->where('a.accountType', $accountType);
                    });
            });

        // 如果有搜索文本，添加标题搜索条件
        if (!empty($searchText)) {
            $query->whereLike('n.title', '%' . $searchText . '%');
        }

        // 查询字段
        $query->field('n.*, a.isRead');

        // 按ID倒序排序
        $query->order('n.id', 'desc');

        // 分页查询
        $paginator = $query->paginate([
            'list_rows' => $limit,
            'page' => $page
        ])->each(function ($item) {
            if (!isset($item['isRead'])) {
                $item['isRead'] = 0;
            }
        });

        return $paginator;
    }


    /**
     * 获取我的未读通知数量
     *
     * @param string $accountId 账户ID
     * @param string $accountType 账户类型
     * @return int
     */
    public function getMyUnreadCount($accountId, $accountType)
    {
        // 使用原生SQL查询
        $sql = "SELECT COUNT(1) AS unreadCount
                FROM (
                    SELECT a.*, b.isRead
                    FROM ba_banxi_sys_notification a
                    LEFT JOIN ba_banxi_sys_notification_accept b ON a.id = b.notificationId AND b.del = 0
                    WHERE a.del = 0
                    AND (a.isAll = 1 OR (a.isAll = 0 AND b.accountId = ? AND b.accountType = ?))
                ) a
                WHERE a.isRead = 0";

        $result = Db::query($sql, [$accountId, $accountType]);

        return (int)($result[0]['unreadCount'] ?? 0);
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


}